﻿using System;
using CRM.Caches;
using CRM.Models;
using CRM.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;

namespace CRM.Extensions
{
    public static class ServiceCollectionExtension
    {
        public static void AddPropertyService<T>(this IServiceCollection services) =>
            services.AddPropertyService(typeof(T));
        
        public static void AddPropertyService(this IServiceCollection services, Type subClass)
        {
            services.AddTransient(subClass, sp =>
            {
                var instance = ActivatorUtilities.CreateInstance(sp, subClass);
                // TODO: 基类提取到参数，属性反射设置
                if (instance is BaseService service)
                {
                    service.HttpContext = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
                    service.Cache = sp.GetRequiredService<IMemoryCache>();
                    service.UserManager = sp.GetRequiredService<UserManager<User>>();
                    service.DbContext = sp.GetRequiredService<MyDbContext>();
                    var userCache = sp.GetRequiredService<UserCache>();
                    if (service.HttpContext != null)
                        service.CurrentUser = userCache.GetOrCreateAsync(service.DbContext, service.UserManager, service.HttpContext.User).Result;
                }

                return instance;
            });
        }
    }
}